var getOptionsSetting = () => {
  return new Promise(resolve => {
    // 异步获取存储数据
    chrome.storage.sync.get(['isReplaceGoogleCDN', 'pageLang'], result => {
      resolve({
        isReplaceGoogleCDN: result.isReplaceGoogleCDN || true,
        pageLang: result.pageLang || 'https://zh.forvo.com/search/',
      })
    })
  })
}

/**
 * 设置谷歌 CDN 替换
 * @param {boolean} isReplaceGoogleCDN
 */
const setupReplaceGoogleCDN = (() => {
  const onBeforeRequest = chrome.webRequest.onBeforeRequest

  // chrome.webRequest.onBeforeRequest 事件监听器的回调函数
  const beforeRequestCallback = details => {
    let url = details.url.replace('googleapis.com', 'proxy.ustclug.org')
    url = url.replace(
      'themes.googleusercontent.com',
      'google-themes.lug.ustc.edu.cn'
    )
    url = url.replace(
      'www.google.com/recaptcha/',
      'www.recaptcha.net/recaptcha/'
    )
    return { redirectUrl: url }
  }

  return isReplaceGoogleCDN => {
    if (isReplaceGoogleCDN) {
      // 开启谷歌 CDN 替换
      onBeforeRequest.addListener(
        beforeRequestCallback,
        {
          urls: [
            '*://ajax.googleapis.com/*',
            '*://themes.googleusercontent.com/*',
            '*://www.google.com/recaptcha/*',
          ],
        },
        ['blocking']
      )
    } else {
      // 若已开启，则关闭谷歌 CDN 替换
      if (onBeforeRequest.hasListener(beforeRequestCallback)) {
        onBeforeRequest.removeListener(beforeRequestCallback)
      }
    }
    console.log(
      'chrome.webRequest.onBeforeRequest.hasListener',
      onBeforeRequest.hasListener(beforeRequestCallback)
    )
  }
})()

/**
 * 设置右键菜单项
 * @param {string} searchHost
 */
const setupContextMenu = (() => {
  // 右键菜单项的 ID
  let contextMenusID = null

  const openForvoSearchTab = searchHost => {
    return (info, tab) => {
      var url = encodeURI(`${searchHost}${info.selectionText}`)
      chrome.tabs.create({
        index: tab.index + 1,
        url: url,
      })
    }
  }

  return searchHost => {
    if (!contextMenusID) {
      contextMenusID = chrome.contextMenus.create({
        type: 'normal',
        title: '使用Forvo搜索 "%s"',
        contexts: ['selection'],
        onclick: openForvoSearchTab(searchHost),
      })
    } else {
      chrome.contextMenus.update(contextMenusID, {
        onclick: openForvoSearchTab(searchHost),
      })
    }
  }
})()

getOptionsSetting().then(result => {
  let isReplaceGoogleCDN = result.isReplaceGoogleCDN
  let searchHost = result.pageLang
  setupReplaceGoogleCDN(isReplaceGoogleCDN)
  setupContextMenu(searchHost)
})

// 监听 storage 值的改变
chrome.storage.onChanged.addListener(changes => {
  if (changes.isReplaceGoogleCDN) {
    console.log('chrome.storage.onChanged', changes.isReplaceGoogleCDN)
    setupReplaceGoogleCDN(changes.isReplaceGoogleCDN.newValue)
  }
  if (changes.pageLang) {
    console.log('chrome.storage.onChanged', changes.pageLang)
    setupContextMenu(changes.pageLang.newValue)
  }
})
